<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="../css/Buttons.css" type="text/css" rel="stylesheet"/>
    <link href="../css/project.css" type="text/css" rel="stylesheet"/>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background: gray;
        }

        #chatBox {
            position: relative;
            margin: 0 auto;
            margin-top: 100px;
            width: 720px;
        }

        #msgBox {
            float: left;
            width: 500px;
            margin: 10px;
        }

        #customServiceBox {
            float: right;
            width: 150px;
            height: 400px;
            margin: 10px;
            border: 2px solid black;
            background: white;
            border-radius: 10px;
            padding: 10px;
            text-align: center;
        }

        .csB-Item {
            text-align: center;
            width: 100px;
            border-radius: 5px;
            overflow: hidden;
            margin: 0 auto;
            margin-top: 20px;
        }
        .csB-Item-Title {
            width: 100%;
            background: #1B9AF7;
        }
        .csB-Item-Content {
            width: 100%;
            background: black;
            color: white;
        }

        .waiting {
            position: absolute;
            width: 100%;
            height: 800px;
            z-index: 100;
            background: rgba(102,102,102, 0.6);
            filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99666666, endColorstr=#99666666);
        }
    </style>
</head>
<body>
<div id="chatBox" class="clearfix">
    <div id="msgBox">

    </div>
    <div id="customServiceBox"></div>
    <div class="waiting">Waiting for Custom Service...</div>
</div>
<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/buttons.js"></script>
<script>
    $(document).ready(function () {
        $.get("/chat/loggedIn", function (result) {
            if (result.status) {
                userJSON = result.data;
                let clientChat = new ClientChat(userJSON, "");
            }
            else {
                alert("no login");
            }
        });
    });
    let userJSON;
    class ClientChat {
        constructor(userJSON, targetDivId) {
            this.state = {
                pushCustomServiceRequest: 0,
                getCustomService: 1,
                getMsg: 2
            };
            this.msgState = {
                msg: 1,
                end: 2
            };
            this.currentState = this.state.pushCustomServiceRequest;
            this.userJSON = userJSON;
            this.loadingUrl = "chrome-extension://hlppekcioiicbfafmmgikkdkljnjpiao/images/loading.gif";
            this.pushCustomServiceRequestUrl = "/chat/pushCustomServiceRequest";
            this.getCustomServiceUrl = "/chat/getCustomService";
            this.getMsgUrl = "/chat/getMsg";
            this.sendMsgUrl = "/chat/sendMsg";
            this.chatEnd = true;
            this.autoScroll = true;
            this.msgBox = $("#msgBox");
            this.customServiceBox = $("#customServiceBox");
            this.waitingBox = $(`.waiting`);

            this.clientChatDiv = $(targetDivId);
            this.ajaxController(this.currentState);
            console.log(this.state);
        }

        dealCustomServiceJSON() {
            this.customServiceJSON.chattingEle = $(`<div class='chatting-Head'>` +
                `<div class='chatting-Head-Setting'>` +
                `<div class='chatting-Head-Setting-Inner'></div>` +
                `</div>` +
                `<div class='chatting-Head-Title'>${this.customServiceJSON.cs_name}</div>` +
                `</div>` +
                `<div class='chatting-Body'>` +
                `<div class='chatting-Body-TextArea'></div>` +
                `</div>` +
                `<div class='chatting-Footer'>` +
                `<div class='chatting-Footer-Upload'>` +
                `<span class='button-dropdown button-dropdown-inverse' data-buttons='dropdown'>` +
                `<button style='color: black;' class='button button-borderless button-icon-txt-large'>+</button>` +
                `<ul style='width: 100px' class='button-dropdown-list is-below'>` +
                `<li><a href='#' onclick='$(this).next().click(); return false;'>Send Picture</a>` +
                `<input type='file' accept='image/x-png,image/gif,image/jpeg,image/bmp' id='uploadPicture'` +
                ` style='display: none;' onchange=''/></li>` +
                `<li><a href='#' onclick='$(this).next().click(); return false;'>Send Video</a>` +
                `<input type='file' accept='video/webm' id='uploadVideo' style='display: none;' onchange=''/></li>` +
                `</ul>` +
                `</span>` +
                `</div>` +
                `<div class='chatting-Footer-SendBox'>` +
                `<textarea class='sendBox-TextArea'></textarea>` +
                `</div>` +
                `<button class='button button-glow button-border button-rounded button-primary' id='sendBtn${this.customServiceJSON.cs_id}'>Send Message</button>` +
                `</div>`);
            this.msgBox.html(this.customServiceJSON.chattingEle);
            this.customServiceJSON.chattingEle.children(`#sendBtn${this.customServiceJSON.cs_id}`).click(function () {
                if (this.chatEnd) {
                    alert(`Chat END.`);
                    return;
                }
                let msg = this.customServiceJSON.chattingEle.children('.chatting-Footer-SendBox').children('.sendBox-TextArea').val();
                if (msg == null || msg === "") {
                    return;
                }
                this.pushMsgToMsgDialog(true, msg);
                this.sendMsg(msg);
            }.bind(this));
        }

        pushMsgToMsgDialog(directionType, msg) {
            let msgDialog = this.customServiceJSON.chattingEle.children(".chatting-Body-TextArea");
            let direction;
            if (directionType) {
                direction = "Right";
            }
            else {
                direction = "Left";
            }
            let textFlag = ``;
            /*if (directionType) {
                textFlag = `<span class='textArea-Flag'><img src='${this.loadingUrl}' class='textArea-ImgFlag'/></span>`;
            }*/
            let textAreaItemStr = `<div class='textArea-Item clearfix'>` +
                `<div class='textArea-${direction}Item-ProfilePhoto'>` +
                `<img class='img' src='' onerror=''/>` +
                `</div>` +
                `<div class='textArea-${direction}Item-Triangle'></div>` +
                `<div class='textArea-${direction}Item-MsgBox clearfix'>` +
                `<div class='textArea-${direction}Item-MsgDialog'>${msg}</div>${textFlag}` +
                `</div>` +
                `</div>`;
            msgDialog.append(textAreaItemStr);
            if (this.autoScroll) {
                msgDialog.scrollTop(msgDialog[0].scrollHeight);
            }
        }

        ajaxController() {
            switch (this.currentState) {
                case this.state.pushCustomServiceRequest:
                    this.pushCustomServiceRequest();
                    break;
                case this.state.getCustomService:
                    this.getCustomService();
                    break;
                case this.state.getMsg:
                    this.getMsg();
                    break;
            }
        }

        pushCustomServiceRequest() {
            $.get(this.pushCustomServiceRequestUrl, function (result) {
                if (result.status) {
                    this.pushCustomServiceRequestSuc();
                }
                else {
                    this.timeOutToNextAjax();
                }
            }.bind(this));
        }

        pushCustomServiceRequestSuc() {
            this.currentState = this.state.getCustomService;
            this.timeOutToNextAjax();
        }

        getCustomService() {
            $.get(this.getCustomServiceUrl, function (result) {
                if (result.status) {
                    this.customServiceJSON = result.data;
                    console.log(this.customServiceJSON);
                    this.getCustomServiceSuc();
                }
                else {
                    this.timeOutToNextAjax();
                }
            }.bind(this));
        }

        getCustomServiceSuc() {
            this.waitingBox.hide();
            this.chatEnd = false;
            this.currentState = this.state.getMsg;
            this.dealCustomServiceJSON();
            this.updateCustomServiceBox();
            this.timeOutToNextAjax();
        }

        getMsg() {
            $.post(this.getMsgUrl, {}, function (result) {
                if (result.status) {
                    this.dealMsgData(result.data);
                }
                this.timeOutToNextAjax();
            }.bind(this));
        }

        dealMsgData(msgData) {
            if (Array.isArray(msgData)) {
                if (msgData.length > 0)
                    console.log(msgData);
                for (let i = 0; i < msgData.length; i++) {
                    switch (msgData[i].stateNumber) {
                        case this.msgState.msg:
                            this.pushMsgToMsgDialog(false, msgData[i].stateMsg);
                            break;
                        case this.msgState.end:
                            this.chatEnd = true;
                            this.currentState = 0;
                            this.chatEndSuc();
                            this.pushMsgToMsgDialog(false, msgData[i].stateMsg);
                            break;
                    }
                }
            }
            else {
                console.log('not array');
            }
        }

        sendMsg(msg) {
            let sendMsgJSON = { msg: msg };
            $.post(this.sendMsgUrl, sendMsgJSON, function (result) {
                if (result.status) {
                    //
                    this.sendMsgSuc();
                }
            }.bind(this));
        }

        chatEndSuc() {
            this.customServiceBox.append(`<button id="callCustomServiceAgainBtn">Call Custom Service Again.</button>`);
            $(`#callCustomServiceAgainBtn`).click(function () {
                this.currentState = this.state.pushCustomServiceRequest;
                this.waitingBox.show();
            }.bind(this));
        }

        sendMsgSuc() {
            //
            this.customServiceJSON.chattingEle.children('.chatting-Footer-SendBox').children('.sendBox-TextArea').val("");
        }

        updateCustomServiceBox() {
            let content = this.customServiceBox;
            content.html("");
            content.append(`<div class="csB-Item"><div class="csB-Item-Title">Custom Service ID</div>
                <div class="csB-Item-Content">${this.customServiceJSON.cs_id}</div></div>
                <div class="csB-Item"><div class="csB-Item-Title">Custom Service Name</div>
                <div class="csB-Item-Content">${this.customServiceJSON.cs_name}</div></div>
            `);
        }

        timeOutToNextAjax() {
            setTimeout(()=>{this.ajaxController()}, 1000);
        }
    }

</script>
</body>
</html>